<template>
  <div class="d-flex flex-ju-sb back-white" style="padding: 8px 0">
    <div class="d-flex flex-wrap role-tabs over-hidden" :class="visible.tabsBar ? '' : 'hidden-bar'">
      <!--  <li
          v-for="(role, i) of roles"
          :key="i"
          class="role-item pointer"
          :class="activeRoleIndex === i && 'active'"
          @click="handleRoleClick(role, i)"
        >
          <span v-show="!role.edit" class="role-item--label">{{ role.roleName }}</span>
          <Input v-show="role.edit" @click.native.stop="() => {}" v-model="role.roleName_ipt" style="width: 100px" />
          <Checkbox v-show="role.delete" v-model="role.checked" label="" @click.native.stop="() => {}"></Checkbox>
        </li> -->
      <CustomTabs ref="customTabs_ref" :value="tabActiveValue" :tabs="roles" @click="handleTabItemClick">
        <template #default="{ item }">
          <div class="role-item">
            <span v-show="!item.edit" class="role-item--label">{{ item.roleName }}</span>
            <Input
              v-show="item.edit"
              @click.native.stop
              v-model="item.roleName_ipt"
              :maxlength="10"
              style="width: 100px"
            />
            <Checkbox v-show="item.delete" v-model="item.checked" label="" @click.native.stop></Checkbox>
          </div>
        </template>
      </CustomTabs>

      <transition name="fade">
        <div v-show="visible.addRole" class="role-item over-hidden">
          <Input
            v-model="addRoleVal"
            @keydown.native.enter="handleRoleComplete"
            placeholder="请输入"
            :maxlength="10"
            style="width: 100px"
          />
        </div>
      </transition>
      <div v-show="visible.operation" class="d-flex flex-a-c">
        <icon-button
          icon="complete"
          title="完成"
          class="ml14"
          :activated="false"
          @click.native="handleRoleComplete"
        ></icon-button>
        <icon-button
          icon="close"
          title="取消"
          class="ml14"
          :activated="false"
          @click.native="handleRoleCancel"
        ></icon-button>
      </div>
    </div>

    <div class="d-flex flex-a-c flex-shrink-0">
      <Button class="mr10" type="primary" @click="handleAddRole" :disabled="operRoleBtnDisabled('add')">
        新增角色
      </Button>
      <Button class="mr10" type="primary" @click="handleRoleEdit" :disabled="operRoleBtnDisabled('edit')">
        编辑角色
      </Button>
      <Button type="primary" @click="handleRoleDelete" :disabled="operRoleBtnDisabled('delete')">删除角色</Button>
      <Form
        class="custom-ivu-form d-inline-block ml14"
        inline
        style="vertical-align: 5px"
        @submit.native.prevent="handleFormSubmit"
      >
        <FormItem style="margin-bottom: 0">
          <Input
            v-model="formData.searchWords"
            :label-width="60"
            placeholder="请输入"
            class="form-item--width"
            size="large"
            clearable
          ></Input>
          <button class="button-empty-style ml5" type="submit">
            <Icon class="f30 pointer" type="ios-search" />
          </button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>

<script>
import CustomTabs from '@/components/common/CustomTabs/CustomTabs'

import {
  // getSystemRoleList,
  postSystemRoleInsert,
  postSystemRoleUpdate,
  postSystemRoleDelete,
} from '@/api/system/roleConfig.js'

import { handleRequestStatus } from '@/utils/uitls.js'

// vuex
import { createNamespacedHelpers } from 'vuex'
const { mapActions } = createNamespacedHelpers('system')
export default {
  name: 'RoleTabs',

  components: { CustomTabs },

  data() {
    return {
      tabActiveValue: '',
      activeRoleIndex: 0,
      roles: [
        /* { label: '超级管理员', value: '1', edit: false, delete: false, active: true, checked: false },
        { label: '主编', value: '5', edit: false, delete: false, active: false, checked: false }, */
      ],

      currentClickBtn: '', // 当前点击的按钮
      addRoleVal: '',
      formData: { searchWords: '' },

      visible: {
        addRole: false,
        showClose: true,
        operation: false,
        tabsBar: true,
      },
    }
  },

  computed: {
    roleList() {
      return this.$store.getters.roleList
    },
  },

  watch: {
    roleList: {
      handler(data) {
        // console.log('roleList', data)
        if (!data.length) {
          this.roles = []
          return
        }
        this.roles = data.map((it) => ({
          edit: false,
          delete: false,
          checked: false,
          roleName_ipt: it.roleName,
          value: it.roleId,
          ...it,
        }))
        const i = this.roles.length - 1 < this.activeRoleIndex ? 0 : this.activeRoleIndex
        this.handleTabItemClick(this.roles[i], i)
        // console.log('roles', this.roles)
      },
      immediate: true,
    },
  },

  methods: {
    ...mapActions(['getSystemRoleList']),

    handleTabItemClick(role, i) {
      this.tabActiveValue = role.roleId
      this.activeRoleIndex = i
      this.$emit('on-tab-change', role, { ...this.formData })
    },

    handleRoleClick(role, i) {
      this.activeRoleIndex = i
      this.$emit('on-tab-change', role, { ...this.formData })
    },

    setVisibleValue(k, v) {
      this.visible[k] = v
    },

    operRoleBtnDisabled(btn) {
      return Boolean(this.currentClickBtn && this.currentClickBtn !== btn)
    },

    handleFormSubmit() {
      this.$emit('on-search-user', { ...this.formData })
    },

    /* 新增角色 */
    handleAddRole() {
      this.currentClickBtn = 'add'
      this.setVisibleValue('addRole', true)
      this.setVisibleValue('operation', true)
    },

    /* 编辑 */
    setRolesState(state, k = 'edit') {
      this.roles.forEach((it) => (it[k] = state))
    },
    handleRoleEdit() {
      this.currentClickBtn = 'edit'
      this.setVisibleValue('tabsBar', false)
      this.setRolesState(true)
      this.setVisibleValue('operation', true)
      this.$refs['customTabs_ref'].updateBar()
    },

    /* 删除 */
    handleRoleDelete() {
      this.currentClickBtn = 'delete'
      this.setVisibleValue('tabsBar', false)
      this.setRolesState(true, 'delete')
      this.setVisibleValue('operation', true)
    },

    /* 取消和确定 */
    handleRoleComplete() {
      switch (this.currentClickBtn) {
        case 'add':
          if (!this.addRoleVal.trim()) return
          this.postSystemRoleInsert({ roleName: this.addRoleVal })
          break
        case 'edit':
          this.handleRolesEdit()
          break
        case 'delete':
          this.handleRolesDelete()
          this.handleRoleCancel()
          break
        default:
          console.error('error handle event')
      }
    },
    handleRoleCancel(event) {
      this.addRoleVal = ''
      this.currentClickBtn = ''
      this.setVisibleValue('tabsBar', true)
      this.setVisibleValue('operation', false)
      this.setVisibleValue('addRole', false)
      this.setRolesState(false)
      this.setRolesState(false, 'delete')
      this.$refs['customTabs_ref'].updateBar()
      // 点击取消按钮时再重置
      if (event && event.target) {
        this.roles.forEach((it) => (it.roleName_ipt = it.roleName))
      }
    },

    async handleRolesEdit() {
      // 输入和原来的相同
      const allSame = this.roles.every((it) => it.roleName_ipt === it.roleName)
      if (allSame) {
        return
      }
      for (let i = 0, len = this.roles.length; i < len; i++) {
        const c = this.roles[i]
        const res = await this.postSystemRoleUpdate({ roleName: c.roleName_ipt, roleId: c.roleId })
        if (res.msg === 'failed') {
          this.$Message.error(res.message || '编辑失败')
          return
        } else if (i === len - 1) {
          this.$Message.success(res.message || '编辑成功')
          this.handleRoleCancel()
        }
      }
      this.getSystemRoleList()
    },

    async handleRolesDelete() {
      if (this.roles.every((it) => !it.checked)) return
      const deleteItems = this.roles.filter((it) => it.checked)
      for (let i = 0, len = deleteItems.length; i < len; i++) {
        const c = deleteItems[i]
        const res = await this.postSystemRoleDelete({ roleId: c.roleId })
        if (res.msg === 'failed') {
          this.$Message.error(res.message || '删除失败')
          return
        } else if (i === len - 1) {
          this.$Message.success(res.message || '删除成功')
        }
      }
      this.getSystemRoleList()
    },

    /* 新增 */
    async postSystemRoleInsert(params) {
      const res = await postSystemRoleInsert(params)
      handleRequestStatus(res, '新增', () => {
        this.getSystemRoleList()
        this.handleRoleCancel()
        this.addRoleVal = ''
      })
    },

    /* 修改 */
    async postSystemRoleUpdate(params) {
      const res = await postSystemRoleUpdate(params)
      if (res.data.status === 0) {
        return { msg: 'success', ...res.data }
      } else {
        return { msg: 'failed', ...res.data }
      }
    },

    /* 删除 */
    async postSystemRoleDelete(params) {
      const res = await postSystemRoleDelete(params)
      if (res.data.status === 0) {
        return { msg: 'success', ...res.data }
      } else {
        return { msg: 'failed', ...res.data }
      }
    },
  },

  mounted() {
    // this.getSystemRoleList()
  },
}
</script>

<style lang="less" scoped>
.role-tabs {
  /deep/ .tabs-bar {
    bottom: 16px;
  }

  /deep/ .tab-item {
    margin: 0 14px;
  }
}
.role-tabs.hidden-bar {
  /deep/ .tabs-bar {
    display: none;
  }
}

.role-item {
  position: relative;
  height: 50px;
  line-height: 50px;
  // margin: 0 14px;

  /deep/ .ivu-checkbox-wrapper {
    position: absolute;
    top: -20px;
    right: -10px;
  }
}

.role-item.active {
  .role-item--label {
    color: var(--app-text-active);
    border-bottom: 2px solid currentColor;
  }
}
</style>
